package com.codemate.interview.rabbit;

import com.codemate.interview.constant.RabbitConstant;
import java.util.HashMap;
import java.util.Map;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * rabbit-delay配置
 *
 * @author hice
 */
@Configuration
public class RabbitDelayConfig {

    /**
     * 延时交换机
     *
     * @return .
     */
    @Bean
    public DirectExchange delayExchange() {
        return new DirectExchange(RabbitConstant.DELAY_EXCHANGE_KEY, true, false);
    }

    /**
     * 延时队列
     *
     * @return .
     */
    @Bean
    public Queue delayQueue() {
        Map<String, Object> params = new HashMap<>(3);
        // x-dead-letter-exchange 声明了队列里的死信转发到的DLX名称，
        params.put("x-dead-letter-exchange", RabbitConstant.DELAY_QUEUE_KEY);
        // x-dead-letter-routing-key 声明了这些死信在转发时携带的 routing-key 名称。
        params.put("x-dead-letter-routing-key", RabbitConstant.DELAY_ROUTING_KEY);
        // x-message-ttl 声明该队列死信可存活时间
        params.put("x-message-ttl", RabbitConstant.DELAY_TTL);
        return new Queue(RabbitConstant.DELAY_QUEUE_KEY, true, false, false, params);
    }

    /**
     * 延时队列 根据路由 绑定交换机
     *
     * @return .
     */
    @Bean
    public Binding delayBinding() {
        return BindingBuilder.bind(delayQueue()).to(delayExchange()).with(RabbitConstant.DELAY_ROUTING_KEY);
    }

    /**
     * 可变延时交换机
     *
     * @return .
     */
    @Bean
    public DirectExchange variableDelayExchange() {
        return new DirectExchange(RabbitConstant.DELAY_VARIABLE_EXCHANGE_KEY, true, false);
    }

    /**
     * 可变延时队列
     *
     * @return .
     */
    @Bean
    public Queue variableDelayQueue() {
        Map<String, Object> params = new HashMap<>(2);
        // x-dead-letter-exchange 声明了队列里的死信转发到的DLX名称，
        params.put("x-dead-letter-exchange", RabbitConstant.DELAY_VARIABLE_EXCHANGE_KEY);
        // x-dead-letter-routing-key 声明了这些死信在转发时携带的 routing-key 名称。
        params.put("x-dead-letter-routing-key", RabbitConstant.DELAY_VARIABLE_ROUTING_KEY);
        return new Queue(RabbitConstant.DELAY_VARIABLE_QUEUE_KEY, true, false, false, params);
    }

    /**
     * 可变延时队列 根据路由 绑定交换机
     *
     * @return .
     */
    @Bean
    public Binding variableDelayBinding() {
        return BindingBuilder.bind(variableDelayQueue()).to(variableDelayExchange())
            .with(RabbitConstant.DELAY_VARIABLE_ROUTING_KEY);
    }

}
